package com.jolink.omiis.wechat.util;

import java.io.File;
import java.io.IOException;
import java.net.MalformedURLException;
import java.net.URL;
import java.util.Date;

import org.apache.commons.io.FileUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.jolink.omiis.wechat.keys.IPreferences;

/**
 * 文件操作
 * 
 * @author WangYanqing
 *
 */
public class FileUtil {

	private static Logger logger = LoggerFactory.getLogger(FileUtil.class);

	/**
	 * 
	 * 获取全媒体存储路径
	 * 
	 * @return
	 */
	public static String getMultiMediaPath() {
		return WeChatConfiguration.getIngleton().getValue("OMIIS_MATERIAL_UPLOAD_PATH") + File.separator
				+ DateUtil.formatDate(new Date(), IPreferences.DATE_FORMAT_1);
	}

	public static String getMultiMediaFullPath(String fileName) {
		return WeChatConfiguration.getIngleton().getValue("OMIIS_MATERIAL_BASE_URL")
				+ DateUtil.formatDate(new Date(), IPreferences.DATE_FORMAT_1) + File.separator + fileName;
	}

	public static void download(String materialUrl, String filename, String downloadPath) {
		long t1 = System.currentTimeMillis();
		logger.info("开始下载文件，url：{}。", materialUrl);
		URL url = null;
		try {
			url = new URL(materialUrl);
			File file = new File(downloadPath, filename);
			FileUtils.copyURLToFile(url, file);
		} catch (MalformedURLException e) {
			logger.error(e.getMessage(), e);
		} catch (IOException e) {
			logger.error(e.getMessage(), e);
		} finally {

		}
		long t2 = System.currentTimeMillis();
		logger.info("文件下载完成，url：{}，filename：{}，downloadPath：{}，耗时：{}毫秒。", materialUrl, filename, downloadPath,
				(t2 - t1));
	}
}
